using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEditor;
using UnityEngine;
using Yoozoo.Core.Extensions.Engine;

namespace com.yoozoo.gta.Art
{
    public class BeautyGirlController : MonoBehaviour
    {
        [SerializeField][Header("是否默认开启场景漫游相机")]private bool isFreeCamera = false;
        [SerializeField][Header("漫游相机移动速度")]private float freeSpeed = 1.0f;
        [SerializeField][Header("漫游相机加移动倍率")]private float freeSpeedShift = 2.0f;

        [Header("行走速度")]public float walkSpeed = 1.0f;
        [Header("奔跑速度")]public float runSpeed = 2.0f;
        [Header("第一人称相机")]public CinemachineFreeLook firstPersonCamera;
        [Header("第三人称相机")]public CinemachineFreeLook thirdPersonCamera;
        [Header("自由相机")]public CinemachineFreeLook freeCamera;
        private float gravity = -9.81f; // 重力值
        private float verticalVelocity = 0.0f; // 垂直速度
        private string _currAnimStateName = "thisState"; // 当前动画名称
        private string _isGoBackParamName = "isGoBack"; // 倒退状态的动画参数名称
        private Camera _mainCamera; // 主相机
        private Animator _animator; // 主角的animator
        private CharacterController _characterController;
        private Vector3 _moveDirection;

        public static GameObject CurrPlayer;

        enum AnimState { Idle = 0, Walk = 1, Run = 2 }


        void Awake()
        {
            CurrPlayer = this.gameObject;
        }

        void Start()
        {
            // 隐藏并锁定鼠标
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;

            // 初始时使用第三人称相机
            firstPersonCamera.SetActive(false);
            thirdPersonCamera.SetActive(true);

            _mainCamera = Camera.main;
            _characterController = GetComponent<CharacterController>();
            _animator = GetComponent<Animator>();

            if (isFreeCamera)
            {
                SwitchFreeCamera();
            }
        }

        void Update()
        {
            if (Input.GetKeyUp(KeyCode.P))
            {
                isFreeCamera = isFreeCamera ? false : true;
                SwitchFreeCamera();
            }

            if (!isFreeCamera)
            {
                HandleMovementAndAnimation();
                ApplyGravity();
                SwitchCamera();
            }
            else
            {
                FreeCamera();
            }

        }

        private void SwitchFreeCamera()
        {
            if (isFreeCamera)
            {
                firstPersonCamera.SetActive(false);
                thirdPersonCamera.SetActive(false);
                freeCamera.SetActive(true);
                foreach (var skinnedMeshRenderer in _characterController.transform.GetComponentsInChildren<SkinnedMeshRenderer>())
                {
                    if(skinnedMeshRenderer.enabled == true)
                    {
                        skinnedMeshRenderer.enabled = false;
                    }
                }

            }else{
                firstPersonCamera.SetActive(false);
                thirdPersonCamera.SetActive(true);
                freeCamera.SetActive(false);
                foreach (var skinnedMeshRenderer in _characterController.transform.GetComponentsInChildren<SkinnedMeshRenderer>())
                {
                    if(skinnedMeshRenderer.enabled == false)
                    {
                        skinnedMeshRenderer.enabled = true;
                    }
                }
            }
        }
        private void FreeCamera()
        {
            // 获取鼠标输入以控制视角旋转
            float mouseX = Input.GetAxis("Mouse X");
            float mouseY = Input.GetAxis("Mouse Y");

            // 定义鼠标灵敏度
            float sensitivity = 100.0f;
            float rotationX = mouseX * sensitivity * Time.deltaTime;
            float rotationY = mouseY * sensitivity * Time.deltaTime;

            // 调整相机的旋转
            Vector3 currentRotation = freeCamera.transform.eulerAngles;
            currentRotation.x -= rotationY; // 反转Y轴方向
            currentRotation.y += rotationX;
            freeCamera.transform.eulerAngles = currentRotation;

            // 根据键盘输入控制相机位移方向
            Vector3 _moveDirection = Vector3.zero;
            if (Input.GetKey(KeyCode.W))
            {
                _moveDirection += freeCamera.transform.forward;
            }
            if (Input.GetKey(KeyCode.S))
            {
                _moveDirection -= freeCamera.transform.forward;
            }
            if (Input.GetKey(KeyCode.A))
            {
                _moveDirection -= freeCamera.transform.right;
            }
            if (Input.GetKey(KeyCode.D))
            {
                _moveDirection += freeCamera.transform.right;
            }
            if (Input.GetKey(KeyCode.Q))
            {
                _moveDirection -= freeCamera.transform.up;
            }
            if (Input.GetKey(KeyCode.E))
            {
                _moveDirection += freeCamera.transform.up;
            }

            // 规范化方向向量，防止对角移动速度过快
            _moveDirection.Normalize();

            // 判断是否按下左Shift以加速
            float speed = freeSpeed;
            if (Input.GetKey(KeyCode.LeftShift))
            {
                speed *= freeSpeedShift;
            }

            // 移动相机
            freeCamera.transform.Translate(_moveDirection * speed * Time.deltaTime, Space.World);
        }


        //切换第一人称和第三人称相机
        public void SwitchCamera()
        {
            if (Input.GetKeyDown(KeyCode.V))
            {
                firstPersonCamera.SetActive(!firstPersonCamera.isActiveAndEnabled);
                thirdPersonCamera.SetActive(!thirdPersonCamera.isActiveAndEnabled);

                foreach (var skinnedMeshRenderer in _characterController.transform.GetComponentsInChildren<SkinnedMeshRenderer>())
                {
                    if (skinnedMeshRenderer.enabled == true)
                    {
                        skinnedMeshRenderer.enabled = false;
                    }else{
                        skinnedMeshRenderer.enabled = true;
                    }

                }
            }
        }

        void ApplyGravity()
        {
            if (_characterController.isGrounded)
            {
                // 当角色在地面上时，垂直速度为0
                verticalVelocity = 0.0f;
            }
            else
            {
                // 当角色不在地面上时，受重力影响
                verticalVelocity += gravity * Time.deltaTime;
            }

            // 应用垂直方向的速度
            Vector3 gravityMove = new Vector3(0, verticalVelocity, 0);
            _characterController.Move(gravityMove * Time.deltaTime);
        }

        void HandleMovementAndAnimation()
        {
            HandleInput(out float moveSpeed, out bool isRunning, out bool isGoingBack);
            PlayAnim(isRunning ? AnimState.Run : moveSpeed == 0 ? AnimState.Idle : AnimState.Walk, isGoingBack);
            Move(moveSpeed);
        }

        void HandleInput(out float moveSpeed, out bool isRunning, out bool isGoingBack)
        {
            moveSpeed = 0;
            isRunning = false;
            isGoingBack = false;

            if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.LeftShift))
            {
                moveSpeed = runSpeed;
                isRunning = true;
            }
            else if (Input.GetKey(KeyCode.W))
            {
                moveSpeed = walkSpeed;
            }else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.LeftShift))
            {
                moveSpeed = -runSpeed;
                isRunning = true;
                isGoingBack = true;
            }
            else if (Input.GetKey(KeyCode.S))
            {
                moveSpeed = -walkSpeed * 0.5f;
                isGoingBack = true;
            }
        }

        void PlayAnim(AnimState animState, bool isGoBack)
        {
            if (_animator.GetInteger(_currAnimStateName) != (int)animState)
            {
                _animator.SetInteger(_currAnimStateName, (int)animState);
            }

            if (_animator.GetBool(_isGoBackParamName) != isGoBack)
            {
                _animator.SetBool(_isGoBackParamName, isGoBack);
            }
        }

        void Move(float moveSpeed)
        {
            // 获取相机的前向方向，忽略y轴
            _moveDirection = _mainCamera.transform.forward;
            _moveDirection.y = 0;
            _moveDirection.Normalize();

            // 根据移动速度方向进行反向调整
            if (moveSpeed < 0)
            {
                _moveDirection = -_moveDirection;
            }

            // 使用 CharacterController 移动角色
            _characterController.Move(_moveDirection * Mathf.Abs(moveSpeed) * Time.deltaTime);

            // 角色朝向移动的方向，使用局部旋转
            //if (moveSpeed != 0)
            //{
                Quaternion targetRotation = Quaternion.LookRotation(_moveDirection);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 0.1f);
            //}
        }
    }
#if UNITY_EDITOR
    [CustomEditor(typeof(BeautyGirlController))]
    public class BeautyGirlControllerInfo : Editor
    {
        private BeautyGirlController _target;

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            EditorGUILayout.HelpBox("V 键：第一、三人称。 \n" +
                                    "P 键：角色控制、3D空间自由移动相机。\n" +
                                    "W、S、A、D : 前后左右位移。\n" +
                                    "E、Q : 上下位移。"
                ,MessageType.Info);
        }
    }
#endif
}
